<template>
  <!-- 年级下拉弹窗 -->
  <van-popup v-model:show="showPopup" round position="bottom">
    <van-cascader
      v-model="no"
      :options="allGradeInfo"
      :field-names="{ text: 'gradeName', value: 'gradeNo' }"
      @close="showPopup = false"
      @change="cascaderChange"
    >
      <template #title>
        <span style="position: relative; top: 5px">请选择年级</span>
        <van-button
          class="cascader-btn"
          type="primary"
          size="mini"
          @click.stop="clearGrade"
        >
          删除已选值
        </van-button>
      </template>
    </van-cascader>
  </van-popup>
</template>

<script lang="ts" setup>
import { useVModels } from '@vueuse/core'
import { onBeforeMount, ref } from 'vue'
import { Grade } from '../types'
import axios from '/@/api/axios'
const props =
  defineProps<{ gradeNo: string; gradeName: string; show: boolean }>()

const emits = defineEmits(['update:gradeNo', 'update:gradeName', 'update:show'])

const { gradeNo: no, gradeName, show: showPopup } = useVModels(props, emits)

function clearGrade() {
  no.value = ''
  gradeName.value = ''
  showPopup.value = false
}

async function cascaderChange(op: any) {
  gradeName.value = op.selectedOptions.find(
    (s: any) => s['gradeNo'] === op.value
  )['gradeName']
  showPopup.value = false
}

const { allGradeInfo } = useGradeInfo()

function useGradeInfo() {
  const allGradeInfo = ref<Grade[]>([])
  onBeforeMount(() => {
    axios.get(`/api/blade-system/grade/list`).then((res) => {
      allGradeInfo.value = res.data.data || []
    })
  })

  return { allGradeInfo }
}
</script>

<style lang="less" scoped>
.cascader-btn {
  margin-left: 10px;
  background-color: #4792c5;
  border: 0;
}
</style>
